import {Injectable} from "@angular/core";
import {UnlockService} from "../native/authentication/authentication.service";
import {ToastService} from "./toast.service";
import {HttpClient} from "@angular/common/http";
import {error} from "util";
import {Events} from "ionic-angular";

@Injectable()
export class CaptchaService {
    private modal: HTMLElement;
    private captcha: any;
    // private errorCount: number;

    constructor(private unlockService: UnlockService,
                private http: HttpClient,
                private events: Events,
                private toastService: ToastService) {
        this.modal = null;
    }

    public init(element: HTMLElement) {
        if (typeof element === "undefined" || element == null) {
            return;
        }
        this.modal = element;
        this.modal.hidden = true;
        // this.createContainer();
        this.initCaptcha();

    }

    public show() {
        if (this.modal == null) {
            return;
        }
        this.modal.hidden = false;
        this.captcha.reset();
    }

    public hide() {
        if (this.modal == null) {
            return;
        }
        this.modal.hidden = true;
    }

    private initCaptcha() {
        const verifySig = this.unlockService.verifyCaptchaSignature;
        let self = this;
        // self.errorCount = 0;
        let noCAPTCHA = window['NoCaptcha'];
        let nc_token = ["'FFFF0N00000000005DBB'", (new Date()).getTime(), Math.random()].join(':');
        let nc = noCAPTCHA.init({
            renderTo: '#captcha',
            appkey: 'FFFF0N00000000005DBB', //'CF_APP_1'
            scene: 'nc_login_h5',
            token: nc_token,
            //trans: { "key1": "code200" },
            //elementID: ["usernameID"],
            //is_Opt: 0,
            //language: "cn",
            //timeout: 10000,
            //retryTimes: 5,
            errorTimes: 5,
            bannerHidden: false,
            // initHidden: false,
            inline: true,
            apimap: {},
            callback: (data) => {
                verifySig.call(this.unlockService, nc_token, "nc_login_h5", data.csessionid, data.sig).then(result=>{
                    this.hide();
                    localStorage.setItem('requestId', result.requestId);
                }, ()=>{
                    this.toastService.showToast('啊哦，服务器开小差了，请稍后重试');
                    this.show()
                });
            },
            error: () => {
            }
        });
        nc.on("beforeverify", () => {
            //弹出验证浮层之前
        });
        nc.on("afterverify", () => {
            //弹出验证浮层之后
            if (navigator.onLine) {
                let el = this.modal.querySelectorAll('.btn-ok')[0];
                let inputEl = this.modal.querySelectorAll("input")[0];
                el.innerHTML = '确&nbsp;认';
                el && el.addEventListener("click", function (e) {
                    inputEl && inputEl.blur();
                });
            } else {
                //this.toastService.showToast('当前网络环境异常，请稍后重试', 2000);
                this.events.publish('checkNet');
            }
        });
        nc.on("success", () => {
            //用户验证成功
            this.hide();
        });
        nc.on("error", () => {
            if (!navigator.onLine) {
                this.events.publish('checkNet');
                //this.toastService.showToast('当前网络环境异常，请稍后重试', 2000);
            }
        });
        nc.on("fail", () => {
            //用户验证失败
        });
        nc.on("refresh", () => {
            this.show();
        });
        noCAPTCHA.setEnabled(true);
        nc.reset();//请务必确保这里调用一次reset()方法
        noCAPTCHA.upLang('cn', {
            'SLIDER_LABEL': "滑动通过验证",
            'CHECK_N': "验证失败",
            'TIPS_TITLE': "验证码错误，请重新输入"
        });
        this.captcha = nc;
    }
}
